#include <iostream>
#include <string>
#include "lockGuard.hpp"
#include "pthread.hpp"
#include<unistd.h>

int tickets = 10000;
pthread_mutex_t mutex;

void threadRoutine(void *args) 
{
    std::string name = static_cast<const char *>(args);

    while (true)
    {
        usleep(100);
        {
            lockGuard lockguard(&mutex); // lock_guard
            if (tickets > 0) 
            {
                std::cout << name << " sells ticket: " << tickets << std::endl; 
                tickets--;
            }
            else
            {
                break;
            }
        }
        usleep(100);
    }
}

int main()
{
    pthread_mutex_init(&mutex, nullptr);

    thread t1(1, threadRoutine, (void *)"thread1");
    thread t2(2, threadRoutine, (void *)"thread2");
    thread t3(1, threadRoutine, (void *)"thread3");
    thread t4(1, threadRoutine, (void *)"thread4");

    t1.run();
    t2.run();
    t3.run();
    t4.run();

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    pthread_mutex_destroy(&mutex);
    return 0;
}